import pandas as pd
import json
import copy 
import datetime
from mapping import mapping
from area import Area

areas, sensor2pos, sensor2area, pos2sensor = mapping()

days = [pd.read_csv(f'../../dataset/org/log/day{d}.csv', sep=',').to_numpy() for d in range(1,4)]

tstep = 60 * 1
twin = 60 * 1

def singleDay(day, tstep:int, twin:int):
    day_areas = []
    step_start = day[0][2]
    is_sliding = True
    for step, _ in enumerate(day):
        if day[step][2] - step_start >= tstep:
            is_sliding = False
            step_start = day[step][2]

        if is_sliding is False:
            area2users = {}
            for area in areas:
                area2users[area] = set()

            for offset in range(step, len(day)):
                if (day[offset][2] - twin >= step_start) or offset + 1 >= len(day):
                    day_areas.append({
                        'steps': day[step][2],
                        'areas': area2users
                    })
                    break
                uid = day[offset][0]
                sid = day[offset][1]
                area2users[ sensor2area[sid] ].add(uid)

        is_sliding = True

    return day_areas


def singleDay_num(day, tstep, twin):
    people_last_area = {} # uid->area
    area2users = {}
    for area in areas:
        area2users[area] = set()
    day_areas = []
    step_start = day[0][2]
    is_sliding = True
    for step, _ in enumerate(day):
        if day[step][2] - step_start >= tstep:
            is_sliding = False
            step_start = day[step][2]

        if is_sliding is False:
            
            for offset in range(step, len(day)):
                if (day[offset][2] - twin >= step_start) or offset + 1 >= len(day):
                    day_areas.append({
                        'steps': day[step][2],
                        'areas': copy.deepcopy(area2users)
                    })
                    break
                uid = day[offset][0]
                sid = day[offset][1]
                last_area = people_last_area[uid] if people_last_area.get(uid) is not None else None
                area = sensor2area[sid]
                people_last_area[uid] = area
                if last_area is not None: area2users[last_area].remove(uid)
                area2users[area].add(uid)

        is_sliding = True

    return day_areas



area_filter = ["main_venue","sub_venue_A","sub_venue_B","sub_venue_C","sub_venue_D"]

for i, day in enumerate(days):
    day_areas = singleDay_num(day=day, tstep=tstep, twin=twin)
    data = {'keys':[], 'values':[]}
    for area in areas:
        if area in area_filter:
            data['keys'].append(area)
    for d in day_areas:
        # stime = str(datetime.timedelta(seconds=float(d["steps"])))
        stime = int(d["steps"])
        obj = {'time':stime}
        for area in areas:
            if area in area_filter:
                num = len(d["areas"][area])
                obj[area]=num
        data['values'].append(obj)
    json_str = json.dumps(data)
    with open(f'../../dataset/prcd/day{i+1}.json', 'w') as fout:
        fout.write(json_str)
        fout.flush()
